import { PageContainer } from '@ant-design/pro-components';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useModel } from '@umijs/max';
import './staff.css';
import {
  Button,
  Badge,
  Select,
  Input,
  TreeSelect,
  DatePicker,
  Col,
  Drawer,
  Row,
  Space,
  Table,
  Modal,
  Form,
  message,
  Spin,
  Avatar,
  Tabs,
  Upload,
  Divider,
} from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { UploadOutlined, DeleteOutlined, EditOutlined, FileTextOutlined } from '@ant-design/icons';

// 引入API接口
import { getTableList, getLevelList, addstaff, editstaff, getCompanyList } from '@/api/staff';

const { TabPane } = Tabs;
const { Option } = Select;

export interface TableListItem {
  key: string;
  id: string;
  name: string;
  tel: string;
  sex: string;
  idcard: string;
  birthday: string;
  address: string;
  record: string;
  projectid: string;
  companyid: string;
  bank_card: string;
  bank: string;
  agreement_end: string;
  agreement_num: string;
  base_pay: number;
  create_time: string;
  gradeid: string;
  political_status: string;
  layout: number;
  status: number;
  account: string;
  title: string;
  grade_title: string;
  password?: string; // 密码字段
  personal_social_security: number; // 个人社保基数
  company_social_security: number; // 单位社保基数
  contract_between: Contract[];
  certid: {
    certclassid: string;
    certname?: string; // 证书名称
    obtain_time?: string; // 获取时间
  }[];
  esignconfig: {
    companyname: string;
    companycode: string;
    name: string;
  }[];
  entryTime?: string;
  leaveTime?: string;
  contractPeriod?: string;
  // 新增形象照片字段
  imageUrl?: string;
}

// 合同接口定义
export interface Contract {
  key: string;
  id?: string;
  contractName: string; // 合同名称
  contractType: string; // 合同类型
  contractNumber: string; // 合同编号
  partyAName: string; // 甲方姓名
  partyAIdCard: string; // 甲方身份证号
  partyAPhone: string; // 甲方手机号
  partyACompany: string; // 甲方公司全称
  partyAOrganizationCode: string; // 甲方机构代码
  partyBName: string; // 乙方姓名
  partyBIdCard: string; // 乙方身份证号
  partyBPhone: string; // 乙方手机号
  status: string; // 执行状态
  start_time: string; // 开始时间
  end_time: string; // 结束时间
  files?: FileItem[]; // 上传文件
}

// 文件接口定义
interface FileItem {
  uid: string;
  name: string;
  status: 'uploading' | 'done' | 'error' | 'removed';
  url?: string;
}

export interface TableListParams {
  current?: number;
  pageSize?: number;
  [key: string]: any;
}

export interface ApiResponse<T = any> {
  code?: number;
  data?: T;
  msg?: string;
}

// 档级接口定义 - 扩展以支持树形结构
export interface LevelItem {
  id: string;
  title: string;
  money: string; // 注意：API返回的是字符串类型
  safe: string;
  station: string;
  between: string;
  performance: string;
  pid: string | number | null; // 父级ID，可能是数字、字符串或null
  children?: LevelItem[]; // 子节点
}

// 树形结构节点接口
export interface TreeNode {
  title: string;
  value: string;
  money?: number; // 岗位工资
  children?: TreeNode[];
  [key: string]: any; // 允许其他属性
}

// 公司接口定义
export interface ProjectItem {
  id: string;
  title: string;
  address: string;
  day: string;
  create_time: string;
  long: number;
  small: number;
  student: number;
  one: number;
  two: number;
  three: number;
  foure: number;
}

export interface CompanyItem {
  id: string;
  account: string;
  long: number;
  samll: number;
  student: number;
  one: number;
  two: number;
  three: number;
  foure: number;
  mangage: string;
  project: ProjectItem[];
}

export interface CompanyListItem {
  id: string;
  account: string;
}

// 预设岗位档级与工资对应关系
const positionLevelSalaryMap = {
  P1: 5000,
  P2: 7000,
  P3: 10000,
  P4: 15000,
  P5: 20000,
  P6: 30000,
};

// 合同类型选项
const contractTypeOptions = [
  { value: 'labor', label: '劳动合同' },
  { value: 'dispatch', label: '派遣合同' },
  { value: 'training', label: '培训协议' },
  { value: 'confidential', label: '保密协议' },
  { value: 'other', label: '其他合同' },
];

// 合同状态选项
const contractStatusOptions = [
  { value: 'draft', label: '草稿' },
  { value: 'pending', label: '待签署' },
  { value: 'signed', label: '已签署' },
  { value: 'executing', label: '执行中' },
  { value: 'completed', label: '已完成' },
  { value: 'terminated', label: '已终止' },
];

// 证书类型选项
const certificateTypes = [
  { value: 'diploma', label: '毕业证' },
  { value: 'electrician', label: '电工证' },
  { value: 'driver', label: '驾驶证' },
  { value: 'honor', label: '荣誉证' },
  { value: 'technician', label: '技工证' },
  { value: 'degree', label: '学位证' },
];

// 表格样式
const useStyle = createStyles(({ css, token }) => {
  const { antCls } = token;
  return {
    customTable: css`
      ${antCls}-table {
        ${antCls}-table-container {
          ${antCls}-table-body,
          ${antCls}-table-content {
            scrollbar-width: thin;
            scrollbar-color: #eaeaea transparent;
            scrollbar-gutter: stable;
          }
        }
      }
    `,
    formItemRow: css`
      display: flex;
      gap: 16px;
      margin-bottom: 12px; /* 减少间距使表单更紧凑 */

      > div {
        flex: 1;
      }
    `,
    formItemRowHalf: css`
      display: flex;
      gap: 16px;
      margin-bottom: 12px; /* 减少间距使表单更紧凑 */

      > div {
        flex: 0 0 48%;
      }
    `,
    disabledTip: css`
      color: #888;
      font-size: 12px;
      margin-top: 4px;
    `,
    contractSection: css`
      margin-bottom: 16px; /* 减少间距使表单更紧凑 */
      padding-bottom: 8px; /* 减少间距使表单更紧凑 */
      /* 移除分割线 */
    `,
    uploadZone: css`
      border: 1px dashed #d9d9d9;
      border-radius: 4px;
      padding: 20px;
      text-align: center;
      cursor: pointer;
      transition: border-color 0.3s;

      &:hover {
        border-color: #1890ff;
      }
    `,
    actionButton: css`
      margin-right: 4px;
    `,
    // 树形选择器样式优化
    treeSelectContainer: css`
      .${antCls}-tree-select-dropdown {
        max-height: 400px;
      }
      .${antCls}-tree-title {
        padding: 2px 4px;
        border-radius: 2px;
        &:hover {
          background-color: #f5f5f5;
        }
      }
    `,
  };
});

interface DataType extends TableListItem { }

// 递归函数：将扁平的档级数据转换为树形结构
const buildLevelTree = (items: LevelItem[]): TreeNode[] => {
  if (!items || items.length === 0) {
    return [];
  }

  // 将所有项转换为TreeNode格式
  const nodeMap: Record<string, TreeNode> = {};
  items.forEach((item) => {
    nodeMap[item.id] = {
      title: item.title,
      value: String(item.id),
      money: parseFloat(item.money) || 0,
      ...item,
    };
  });

  // 构建树形结构
  const tree: TreeNode[] = [];
  items.forEach((item) => {
    const node = nodeMap[item.id];
    const parentId = item.pid;

    // 如果是根节点 (pid为0、"0"或null)
    if (!parentId || parentId === 0 || parentId === '0') {
      tree.push(node);
    } else {
      // 如果有父节点，则添加到父节点的children中
      const parentNodeId = String(parentId);
      if (nodeMap[parentNodeId]) {
        if (!nodeMap[parentNodeId].children) {
          nodeMap[parentNodeId].children = [];
        }
        nodeMap[parentNodeId].children!.push(node);
      } else {
        // 父节点不存在时，作为根节点处理
        tree.push(node);
      }
    }
  });
  console.log(tree);

  return tree;
};

const Staff: React.FC = () => {
  const { Search } = Input;
  const [levelValue, setLevelValue] = useState<string>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false); // 区分新增和编辑模式
  const [modalForm] = Form.useForm();
  const [drawerForm] = Form.useForm();
  const [originalTableData, setOriginalTableData] = useState<DataType[]>([]); // 存储原始数据
  const [tableData, setTableData] = useState<DataType[]>([]); // 存储筛选后的数据
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { styles } = useStyle();
  const [open, setOpen] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<DataType | null>(null);

  // 搜索条件状态管理
  const [searchParams, setSearchParams] = useState({
    name: '',
    company: '',
    project: '',
    level: '',
    certificate: '',
    date: null as Dayjs | null,
  });

  // 档级、公司、项目相关状态
  const [levelList, setLevelList] = useState<LevelItem[]>([]);
  const [companyList, setCompanyList] = useState<CompanyListItem[]>([]);
  const [projectList, setProjectList] = useState<ProjectItem[]>([]);
  const [selectedCompany, setSelectedCompany] = useState<string>('');

  // 合同相关状态
  const [contractModalVisible, setContractModalVisible] = useState(false);
  const [isEditContractMode, setIsEditContractMode] = useState(false);
  const [currentContract, setCurrentContract] = useState<Contract | null>(null);
  const [contractForm] = Form.useForm();
  const [fileList, setFileList] = useState<FileItem[]>([]);

  // 使用useMemo缓存树形结构，避免每次渲染都重新计算
  const levelTreeData = useMemo(() => {
    // 只有当levelList有数据时才构建树形结构
    if (levelList.length > 0) {
      const tree = buildLevelTree(levelList);
      console.log('原始档级数据:', levelList);
      console.log('转换后的树形数据:', tree);
      return tree;
    }
    return [];
  }, [levelList]);

  // 定义表格列
  const columns: TableColumnsType<DataType> = [
    {
      title: '姓名',
      width: 100,
      dataIndex: 'name',
      key: 'name',
      fixed: 'left',
      align: 'center',

      render: (text: string, record: DataType) => <a onClick={() => showDrawer(record)}>{text}</a>,
    },
    {
      title: '岗位工资',
      dataIndex: 'base_pay',
      key: 'base_pay',
      fixed: 'left',
      align: 'center',
    },
    {
      title: '岗位档级',
      dataIndex: 'grade_title',
      key: 'grade_title',
      fixed: 'left',
      width: 120,
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 80,
      align: 'center',
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      key: 'birthday',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      key: 'tel',
      align: 'center',
    },
    {
      title: '身份证号',
      dataIndex: 'idcard',
      key: 'idcard',
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      key: 'account',
      align: 'center',
    },
    {
      title: '政治面貌',
      dataIndex: 'political_status',
      key: 'political_status',
      align: 'center',
      width: 120,
    },
    {
      title: '籍贯',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
    },
    {
      title: '学历',
      dataIndex: 'record',
      key: 'record',
      align: 'center',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      align: 'center',
    },
    {
      title: '员工状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (status === 1 ? '在岗' : '离职'),
      align: 'center',
      width: 100,
    },
    {
      title: '用工形式',
      dataIndex: 'layout',
      key: 'layout',
      align: 'center',
      width: 100,
      render: (layout: number) => {
        switch (layout) {
          case 1:
            return '长期派遣';
          case 2:
            return '短期派遣';
          case 3:
            return '学员';
          default:
            return '暂无';
        }
      },
    },
    {
      title: '入职时间',
      dataIndex: 'create_time',
      key: 'create_time',
      align: 'center',
    },
    {
      title: '合同时间区间',
      dataIndex: 'concract_between',
      align: 'center',
      width: 200,
      render: (contract) => `${contract.start_time}-${contract.end_time}`,
    },
    { title: '离职时间', dataIndex: 'leave_time', align: 'center', width: 140 },
    {
      title: '现合同期限',
      dataIndex: 'agreement_num',
      key: 'agreement_num',
      align: 'center',
      width: 130,
    },
    {
      title: '银行卡卡号',
      dataIndex: 'bank_card',
      key: 'bank_card',
      align: 'center',
    },
    {
      title: '工资卡开户行',
      dataIndex: 'bank',
      key: 'bank',
      align: 'center',
      width: 220
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      align: 'center',
      render: () => <a>操作</a>,
    },
  ];

  // 合同表格列定义 - 调整按钮样式和状态显示
  const contractColumns: TableColumnsType<Contract> = [
    {
      title: '合同名称',
      dataIndex: 'contractName',
      key: 'contractName',
      fixed: 'left',
      width: 150,
    },
    {
      title: '乙方姓名',
      dataIndex: 'partyBName',
      key: 'partyBName',
      width: 120,
    },
    {
      title: '合同类型',
      dataIndex: 'contractType',
      key: 'contractType',
      width: 120,
      render: (type: string) => {
        const option = contractTypeOptions.find((item) => item.value === type);
        return option ? option.label : type;
      },
    },
    {
      title: '合同开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      width: 130,
    },
    {
      title: '合同结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      width: 130,
    },
    {
      title: '合同状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => {
        // 去掉状态前面的点点，只显示文本
        const option = contractStatusOptions.find((item) => item.value === status);
        return option ? option.label : status;
      },
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 150,
      render: (_: any, record: Contract) => (
        <Space size="small">
          {/* 签署按钮 - 蓝色 */}
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEditContract(record)}
            size="small"
            className={styles.actionButton}
          >
            签署
          </Button>
          {/* 删除按钮 - 红色 */}
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteContract(record.key)}
            size="small"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 显示详情抽屉
  const showDrawer = useCallback(
    (record?: DataType) => {
      setOpen(true);
      if (record) {
        setCurrentRecord(record);
        // 处理日期字段，确保它们是 dayjs 对象
        const processedRecord = {
          ...record,
          name: record.name,
          phone: record.tel,
          idCard: record.idcard,
          gender: record.sex,
          birthday: record.birthday ? dayjs(record.birthday) : null,
          hometown: record.address,
          positionLevel: record.grade_title,
          positionSalary: record.base_pay,
          education: record.record,
          bankName: record.bank,
          bankCard: record.bank_card,
          politicalStatus: record.political_status,
          companyName: record.account,
          projectName: record.title,
          employmentForm:
            record.layout === 1 ? '1' : record.layout === 2 ? '2' : '3', // 使用数字字符串
          employeeStatus: record.status === 1 ? '1' : '2', // 使用数字字符串
          contractExpireTime: record.agreement_end ? dayjs(record.agreement_end) : null,
          contractTerm: record.agreement_num,
          entryTime: record.entryTime
            ? dayjs(record.entryTime)
            : record.create_time
              ? dayjs(record.create_time)
              : null,
          leaveTime: record.leave_time ? dayjs(record.leave_time) : null, // 修正离职时间字段名
          password: record.password || '******', // 在抽屉中显示密码字段
          personalSocialSecurity: record.personal_social_security || 0,
          companySocialSecurity: record.company_social_security || 0,
        };
        drawerForm.setFieldsValue(processedRecord);
      } else {
        setCurrentRecord(null);
        drawerForm.resetFields();
      }
    },
    [drawerForm],
  );

  // 关闭抽屉
  const onClose = () => {
    setOpen(false);
  };

  // 打开编辑弹窗 - 移除密码相关处理
  const handleEdit = () => {
    if (currentRecord) {
      setIsEditMode(true);
      setIsModalVisible(true);
      // 将当前记录数据填充到编辑表单，移除密码字段
      const formValues = {
        ...currentRecord,
        phone: currentRecord.tel,
        idCard: currentRecord.idcard,
        gender: currentRecord.sex,
        birthday: currentRecord.birthday ? dayjs(currentRecord.birthday) : null,
        hometown: currentRecord.address,
        positionLevel: currentRecord.grade_title,
        positionSalary: currentRecord.base_pay,
        education: currentRecord.record,
        bankName: currentRecord.bank,
        bankCard: currentRecord.bank_card,
        politicalStatus: currentRecord.political_status,
        companyName: currentRecord.account,
        projectName: currentRecord.title,
        employmentForm: currentRecord.layout?.toString(), // 直接使用数字字符串
        employeeStatus: currentRecord.status === 1 ? '1' : '2', // 使用数字字符串
        contractExpireTime: currentRecord.agreement_end ? dayjs(currentRecord.agreement_end) : null,
        contractTerm: currentRecord.agreement_num,
        entryTime: currentRecord.entryTime
          ? dayjs(currentRecord.entryTime)
          : currentRecord.create_time
            ? dayjs(currentRecord.create_time)
            : null,
        leaveTime: currentRecord.leave_time ? dayjs(currentRecord.leave_time) : null, // 修正离职时间字段名
        personalSocialSecurity: currentRecord.personal_social_security || 0,
        companySocialSecurity: currentRecord.company_social_security || 0,
        // 不包含密码字段
      };
      modalForm.setFieldsValue(formValues);
    }
  };


  // 打开合同新增弹窗
  const showContractModal = () => {
    setIsEditContractMode(false);
    setContractModalVisible(true);
    setCurrentContract(null);
    contractForm.resetFields();
    setFileList([]);

    // 如果有当前员工信息，预填乙方信息
    if (currentRecord) {
      contractForm.setFieldsValue({
        partyBName: currentRecord.name,
        partyBIdCard: currentRecord.idcard,
        partyBPhone: currentRecord.tel,
      });
    }
  };

  // 打开合同编辑弹窗
  const handleEditContract = (contract: Contract) => {
    setIsEditContractMode(true);
    setCurrentContract(contract);
    setContractModalVisible(true);
    setFileList(contract.files || []);

    // 转换日期格式为dayjs对象
    const formValues = {
      ...contract,
      startTime: contract.start_time ? dayjs(contract.start_time) : null,
      endTime: contract.end_time ? dayjs(contract.end_time) : null,
    };

    contractForm.setFieldsValue(formValues);
  };

  // 删除合同
  const handleDeleteContract = (contractKey: string) => {
    if (currentRecord) {
      const updatedContracts = currentRecord.contract_between.filter(
        (contract) => contract.key !== contractKey,
      );

      // 更新当前记录的合同列表
      const updatedRecord = {
        ...currentRecord,
        contract_between: updatedContracts,
      };

      // 更新表格数据
      const updatedTableData = tableData.map((item) =>
        item.key === currentRecord.key ? updatedRecord : item,
      );

      // 同时更新原始数据
      const updatedOriginalData = originalTableData.map((item) =>
        item.key === currentRecord.key ? updatedRecord : item,
      );

      setCurrentRecord(updatedRecord);
      setTableData(updatedTableData);
      setOriginalTableData(updatedOriginalData);
      message.success('合同已删除');
    }
  };

  // 提交合同表单
  const handleContractOk = () => {
    contractForm
      .validateFields()
      .then((values) => {
        if (!currentRecord) {
          message.error('请先选择员工');
          return;
        }

        // 处理表单数据
        const contractData: Contract = {
          key: isEditContractMode && currentContract ? currentContract.key : Date.now().toString(),
          ...values,
          start_time: values.startTime ? values.startTime.format('YYYY-MM-DD') : '',
          end_time: values.endTime ? values.endTime.format('YYYY-MM-DD') : '',
          files: fileList,
        };

        // 移除临时字段
        delete (contractData as any).startTime;
        delete (contractData as any).endTime;

        // 更新合同列表
        let updatedContracts;
        if (isEditContractMode && currentContract) {
          // 编辑现有合同
          updatedContracts = currentRecord.contract_between.map((contract) =>
            contract.key === currentContract.key ? contractData : contract,
          );
        } else {
          // 添加新合同
          updatedContracts = [...currentRecord.contract_between, contractData];
        }

        // 更新当前记录
        const updatedRecord = {
          ...currentRecord,
          contract_between: updatedContracts,
        };

        // 更新表格数据
        const updatedTableData = tableData.map((item) =>
          item.key === currentRecord.key ? updatedRecord : item,
        );

        // 同时更新原始数据
        const updatedOriginalData = originalTableData.map((item) =>
          item.key === currentRecord.key ? updatedRecord : item,
        );

        setCurrentRecord(updatedRecord);
        setTableData(updatedTableData);
        setOriginalTableData(updatedOriginalData);
        setContractModalVisible(false);
        message.success(isEditContractMode ? '合同已更新' : '合同已添加');
      })
      .catch((info) => {
        console.log('验证失败:', info);
      });
  };

  // 处理文件上传变化
  const handleFileChange = ({ fileList: newFileList }: { fileList: FileItem[] }) => {
    setFileList(newFileList);
  };

  // 过滤上传文件类型
  const beforeUpload = (file: File) => {
    const isPDF = file.type === 'application/pdf';
    const isWord =
      file.type === 'application/msword' ||
      file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    const isExcel =
      file.type === 'application/vnd.ms-excel' ||
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    const isImage = file.type.startsWith('image/');

    if (!isPDF && !isWord && !isExcel && !isImage) {
      message.error('只能上传 PDF、Word、Excel 或图片文件!');
      return false;
    }

    const isLt2M = file.size / 1024 / 1024 < 20;
    if (!isLt2M) {
      message.error('文件大小不能超过 20MB!');
      return false;
    }

    return true;
  };

  // 搜索功能实现
  const handleSearch = useCallback(() => {
    // 从原始数据中筛选
    let filteredData = [...originalTableData];

    // 按姓名搜索（支持模糊匹配）
    if (searchParams.name) {
      const nameLower = searchParams.name.toLowerCase();
      filteredData = filteredData.filter(item =>
        item.name && item.name.toLowerCase().includes(nameLower)
      );
    }

    // 按公司筛选
    if (searchParams.company) {
      filteredData = filteredData.filter(item => item.companyid === searchParams.company);
    }

    // 按项目搜索（支持模糊匹配）
    if (searchParams.project) {
      const projectLower = searchParams.project.toLowerCase();
      filteredData = filteredData.filter(item =>
        item.title && item.title.toLowerCase().includes(projectLower)
      );
    }

    // 按档级筛选
    if (searchParams.level) {
      filteredData = filteredData.filter(item => item.gradeid === searchParams.level);
    }

    // 按证书筛选
    if (searchParams.certificate) {
      filteredData = filteredData.filter(item =>
        item.certid && item.certid.some(cert => cert.certclassid === searchParams.certificate)
      );
    }

    // 按月份筛选
    if (searchParams.date) {
      const targetMonth = searchParams.date.format('YYYY-MM');
      filteredData = filteredData.filter(item => {
        const createMonth = dayjs(item.create_time).format('YYYY-MM');
        return createMonth === targetMonth;
      });
    }

    setTableData(filteredData);
  }, [searchParams, originalTableData]);

  // 重置搜索条件
  const handleResetSearch = () => {
    setSearchParams({
      name: '',
      company: '',
      project: '',
      level: '',
      certificate: '',
      date: null,
    });
    setLevelValue('');
    setTableData([...originalTableData]);
  };

  const fetchTableList = async () => {
    setLoading(true);
    try {
      const res: any = await getTableList({});
      console.log('getTableList response:', res);

      if (res && res.data) {
        const formattedData = res.data.map((item: any, index: number) => {
          // 处理合同数据
          let contracts: Contract[] = [];
          if (item.contract_between && item.contract_between.length > 0) {
            contracts = item.contract_between.map((contract: any, cIndex: number) => ({
              key: `${item.id || index}-${cIndex}`,
              id: contract.id,
              contractName: contract.contractName || `合同${cIndex + 1}`,
              contractType: contract.contractType || 'labor',
              contractNumber:
                contract.contractNumber ||
                `HT${item.id || index}${cIndex + 1}${dayjs().format('YYYYMMDD')}`,
              partyAName: contract.partyAName || '甲方代表',
              partyAIdCard: contract.partyAIdCard || '',
              partyAPhone: contract.partyAPhone || '',
              partyACompany: contract.partyACompany || item.account || '某某公司',
              partyAOrganizationCode: contract.partyAOrganizationCode || '',
              partyBName: contract.partyBName || item.name || `员工${index + 1}`,
              partyBIdCard:
                contract.partyBIdCard ||
                item.idcard ||
                `${Math.floor(Math.random() * 100000000000000000)}`,
              partyBPhone:
                contract.partyBPhone || item.tel || `138${Math.floor(Math.random() * 100000000)}`,
              status: contract.status || 'pending',
              start_time: contract.start_time || item.create_time || '2022-01-01',
              end_time: contract.end_time || item.agreement_end || '',
              files: contract.files || [],
            }));
          } else {
            // 为没有合同的员工添加一个默认合同
            contracts = [
              {
                key: `${item.id || index}-0`,
                contractName: `劳动合同${index + 1}`,
                contractType: 'labor',
                contractNumber: `HT${item.id || index}0${dayjs().format('YYYYMMDD')}`,
                partyAName: '甲方代表',
                partyAIdCard: '',
                partyAPhone: '',
                partyACompany: item.account || '某某公司',
                partyAOrganizationCode: '',
                partyBName: item.name || `员工${index + 1}`,
                partyBIdCard: item.idcard || `${Math.floor(Math.random() * 100000000000000000)}`,
                partyBPhone: item.tel || `138${Math.floor(Math.random() * 100000000)}`,
                status: 'pending',
                start_time: item.create_time || '2022-01-01',
                end_time: item.agreement_end || '2025-01-01',
                files: [],
              },
            ];
          }

          let contractPeriod = '';
          if (contracts.length > 0) {
            const latestContract = contracts[contracts.length - 1];
            contractPeriod = `${latestContract.start_time}至${latestContract.end_time}`;
          }

          // 处理证书数据，使用预设的证书类型
          let certificates = [];
          if (item.certid && item.certid.length > 0) {
            certificates = item.certid.map((cert: any, idx: number) => ({
              certclassid: cert.certclassid || idx.toString(),
              certname: cert.certname || certificateTypes[idx % certificateTypes.length].label,
              obtain_time: cert.obtain_time || dayjs().subtract(idx, 'year').format('YYYY-MM-DD'),
            }));
          } else {
            // 默认添加几种证书
            certificates = [
              {
                certclassid: '1',
                certname: '毕业证',
                obtain_time: dayjs().subtract(5, 'year').format('YYYY-MM-DD'),
              },
              {
                certclassid: '2',
                certname:
                  certificateTypes[Math.floor(Math.random() * certificateTypes.length)].label,
                obtain_time: dayjs().subtract(3, 'year').format('YYYY-MM-DD'),
              },
            ];
          }

          return {
            key: item.id || index.toString(),
            id: item.id,
            name: item.name || `员工${index + 1}`,
            tel: item.tel || `138${Math.floor(Math.random() * 100000000)}`,
            sex: item.sex || (Math.random() > 0.5 ? '男' : '女'),
            idcard: item.idcard || `${Math.floor(Math.random() * 100000000000000000)}`,
            birthday: item.birthday || '1990-01-01',
            address: item.address || ['北京', '上海', '广州', '深圳', '杭州'][index % 5],
            record: item.record || ['高中', '大专', '本科', '研究生', '博士'][index % 5],
            projectid: item.projectid || '',
            companyid: item.companyid || '',
            bank_card: item.bank_card || `622200${Math.floor(Math.random() * 100000000000000)}`,
            bank: item.bank || ['工商银行', '建设银行', '农业银行', '中国银行'][index % 4],
            agreement_end: item.agreement_end || '',
            agreement_num: item.agreement_num || '',
            base_pay: item.base_pay || Math.floor(Math.random() * 10000) + 5000,
            create_time: item.create_time || '2022-01-01',
            gradeid: item.gradeid || '',
            political_status: item.political_status || (Math.random() > 0.5 ? '党员' : '群众'),
            layout: item.layout || 3,
            status: item.status !== undefined ? item.status : 1,
            account: item.account || '某某公司',
            title: item.title || `项目${String.fromCharCode(65 + (index % 5))}`,
            grade_title: item.grade_title || `P${Math.floor(Math.random() * 5) + 1}`,
            password: '******', // 密码默认显示为星号
            personal_social_security:
              item.personal_social_security || Math.floor(Math.random() * 5000) + 3000,
            company_social_security:
              item.company_social_security || Math.floor(Math.random() * 8000) + 5000,
            contract_between: contracts,
            certid: certificates,
            esignconfig: item.esignconfig || [],
            contractPeriod,
            ...item,
          };
        });

        setOriginalTableData(formattedData);
        setTableData(formattedData);
      } else {
        // 生成默认数据
        const defaultData: DataType[] = [
          {
            key: '1',
            id: '1',
            name: '张三',
            tel: '13800138000',
            sex: '男',
            idcard: '110101199001011234',
            birthday: '1990-01-01',
            address: '北京',
            record: '本科',
            projectid: '1',
            companyid: '1',
            bank_card: '6222001234567890123',
            bank: '工商银行',
            agreement_end: '2025-01-01',
            agreement_num: '3年',
            base_pay: 8000,
            create_time: '2022-01-01',
            gradeid: '1',
            political_status: '党员',
            layout: 3,
            status: 1,
            account: '某某公司',
            title: '项目A',
            grade_title: 'P3',
            password: '******',
            personal_social_security: 6500,
            company_social_security: 9800,
            contract_between: [
              {
                key: '1-0',
                contractName: '劳动合同1',
                contractType: 'labor',
                contractNumber: `HT10${dayjs().format('YYYYMMDD')}`,
                partyAName: '甲方代表',
                partyAIdCard: '',
                partyAPhone: '',
                partyACompany: '某某公司',
                partyAOrganizationCode: '',
                partyBName: '张三',
                partyBIdCard: '110101199001011234',
                partyBPhone: '13800138000',
                status: 'pending',
                start_time: '2022-01-01',
                end_time: '2025-01-01',
                files: [],
              },
            ],
            certid: [
              { certclassid: '1', certname: '毕业证', obtain_time: '2010-06-30' },
              { certclassid: '2', certname: '电工证', obtain_time: '2015-03-15' },
            ],
            esignconfig: [],
            contractPeriod: '2022-01-01至2025-01-01',
          },
          {
            key: '2',
            id: '2',
            name: '李四',
            tel: '13900139000',
            sex: '女',
            idcard: '110101198505123456',
            birthday: '1985-05-12',
            address: '上海',
            record: '硕士',
            projectid: '2',
            companyid: '1',
            bank_card: '6222001234567890456',
            bank: '建设银行',
            agreement_end: '2024-03-15',
            agreement_num: '3年',
            base_pay: 12000,
            create_time: '2021-03-15',
            gradeid: '2',
            political_status: '群众',
            layout: 1,
            status: 1,
            account: '某某公司',
            title: '项目B',
            grade_title: 'P4',
            password: '******',
            personal_social_security: 8200,
            company_social_security: 12500,
            contract_between: [
              {
                key: '2-0',
                contractName: '劳动合同2',
                contractType: 'labor',
                contractNumber: `HT20${dayjs().format('YYYYMMDD')}`,
                partyAName: '甲方代表',
                partyAIdCard: '',
                partyAPhone: '',
                partyACompany: '某某公司',
                partyAOrganizationCode: '',
                partyBName: '李四',
                partyBIdCard: '110101198505123456',
                partyBPhone: '13900139000',
                status: 'signed',
                start_time: '2021-03-15',
                end_time: '2024-03-15',
                files: [],
              },
            ],
            certid: [
              { certclassid: '3', certname: '学位证', obtain_time: '2008-07-01' },
              { certclassid: '4', certname: '驾驶证', obtain_time: '2012-11-20' },
            ],
            esignconfig: [],
            contractPeriod: '2021-03-15至2024-03-15',
          },
        ];
        setOriginalTableData(defaultData);
        setTableData(defaultData);
      }
    } catch (error) {
      console.error('获取员工列表失败:', error);
      message.error('获取员工列表失败');
      // 错误时显示默认数据
      const defaultData: DataType[] = [
        {
          key: '1',
          id: '1',
          name: '张三',
          tel: '13800138000',
          sex: '男',
          idcard: '110101199001011234',
          birthday: '1990-01-01',
          address: '北京',
          record: '本科',
          projectid: '1',
          companyid: '1',
          bank_card: '6222001234567890123',
          bank: '工商银行',
          agreement_end: '2025-01-01',
          agreement_num: '3年',
          base_pay: 8000,
          create_time: '2022-01-01',
          gradeid: '1',
          political_status: '党员',
          layout: 3,
          status: 1,
          account: '某某公司',
          title: '项目A',
          grade_title: 'P3',
          password: '******',
          personal_social_security: 6500,
          company_social_security: 9800,
          contract_between: [
            {
              key: '1-0',
              contractName: '劳动合同1',
              contractType: 'labor',
              contractNumber: `HT10${dayjs().format('YYYYMMDD')}`,
              partyAName: '甲方代表',
              partyAIdCard: '',
              partyAPhone: '',
              partyACompany: '某某公司',
              partyAOrganizationCode: '',
              partyBName: '张三',
              partyBIdCard: '110101199001011234',
              partyBPhone: '13800138000',
              status: 'pending',
              start_time: '2022-01-01',
              end_time: '2025-01-01',
              files: [],
            },
          ],
          certid: [
            { certclassid: '1', certname: '毕业证', obtain_time: '2010-06-30' },
            { certclassid: '2', certname: '技工证', obtain_time: '2015-03-15' },
          ],
          esignconfig: [],
          contractPeriod: '2022-01-01至2025-01-01',
        },
        {
          key: '2',
          id: '2',
          name: '李四',
          tel: '13900139000',
          sex: '女',
          idcard: '110101198505123456',
          birthday: '1985-05-12',
          address: '上海',
          record: '硕士',
          projectid: '2',
          companyid: '1',
          bank_card: '6222001234567890456',
          bank: '建设银行',
          agreement_end: '2024-03-15',
          agreement_num: '3年',
          base_pay: 12000,
          create_time: '2021-03-15',
          gradeid: '2',
          political_status: '群众',
          layout: 1,
          status: 1,
          account: '某某公司',
          title: '项目B',
          grade_title: 'P4',
          password: '******',
          personal_social_security: 8200,
          company_social_security: 12500,
          contract_between: [
            {
              key: '2-0',
              contractName: '劳动合同2',
              contractType: 'labor',
              contractNumber: `HT20${dayjs().format('YYYYMMDD')}`,
              partyAName: '甲方代表',
              partyAIdCard: '',
              partyAPhone: '',
              partyACompany: '某某公司',
              partyAOrganizationCode: '',
              partyBName: '李四',
              partyBIdCard: '110101198505123456',
              partyBPhone: '13900139000',
              status: 'signed',
              start_time: '2021-03-15',
              end_time: '2024-03-15',
              files: [],
            },
          ],
          certid: [
            { certclassid: '3', certname: '荣誉证', obtain_time: '2008-07-01' },
            { certclassid: '4', certname: '学位证', obtain_time: '2012-11-20' },
          ],
          esignconfig: [],
          contractPeriod: '2021-03-15至2024-03-15',
        },
      ];
      setOriginalTableData(defaultData);
      setTableData(defaultData);
    } finally {
      setLoading(false);
    }
  };

  // 获取档级列表 - 优化为树形结构
  const fetchLevelList = async () => {
    try {
      const res: any = await getLevelList({});
      console.log('档级列表API返回数据:', res);

      if (res && res && res.list && res.list.length > 0) {
        // 使用实际数据
        setLevelList(res.list);
      } else {
        // 没有数据时清空列表
        setLevelList([]);
        console.log('档级列表为空');
      }
    } catch (error) {
      console.error('获取档级列表失败:', error);
      message.error('获取档级列表失败');
      setLevelList([]);
    }
  };

  // 获取公司列表
  const fetchCompanyList = async () => {
    try {
      const res: any = await getCompanyList({});
      if (res && res.data) {
        // 设置公司列表
        setCompanyList(res.companylist || []);

        // 移除了默认选择第一个公司的逻辑
      }
    } catch (error) {
      console.error('获取公司列表失败:', error);
      message.error('获取公司列表失败');
    }
  };

  // 当选择公司时，更新项目列表
  const handleCompanyChange = (companyId: string) => {
    setSelectedCompany(companyId);
    setSearchParams(prev => ({ ...prev, company: companyId }));

    // 查找选中公司的项目列表
    getCompanyList({})
      .then((res: any) => {
        if (res && res.data) {
          const selectedCompany = res.data.find((company: CompanyItem) => company.id === companyId);
          if (selectedCompany && selectedCompany.project) {
            setProjectList(selectedCompany.project);
          } else {
            setProjectList([]);
          }
        }
        handleSearch(); // 公司变更后执行搜索
      })
      .catch((error) => {
        console.error('获取公司详情失败:', error);
        message.error('获取公司详情失败');
      });
  };

  useEffect(() => {
    fetchTableList();
    fetchLevelList();
    fetchCompanyList();
  }, []);

  // 监听表单值变化，实现自动填充功能
  const handleValuesChange = (changedValues: any, allValues: any) => {
    // 身份证号自动填充性别和生日
    if (changedValues.idCard) {
      const idCard = changedValues.idCard.trim();
      if (idCard.length === 18) {
        // 提取生日 (第7-14位)
        const birthdayStr = idCard.substring(6, 14);
        const birthday = `${birthdayStr.substring(0, 4)}-${birthdayStr.substring(4, 6)}-${birthdayStr.substring(6, 8)}`;

        // 提取性别 (第17位，奇数为男，偶数为女)
        const genderCode = parseInt(idCard.substring(16, 17), 10);
        const gender = genderCode % 2 === 1 ? '男' : '女';

        // 设置表单值
        const form = currentRecord ? drawerForm : modalForm;
        form.setFieldsValue({
          birthday: dayjs(birthday),
          gender,
        });
      }
    }

    // 岗位档级自动填充岗位工资
    if (changedValues.positionLevel) {
      // 从树形结构中查找对应的档级数据
      const findLevelSalary = (nodes: TreeNode[], levelId: string): number => {
        for (const node of nodes) {
          if (node.value === levelId) {
            return node.money || 0;
          }
          if (node.children && node.children.length > 0) {
            const salary = findLevelSalary(node.children, levelId);
            if (salary !== undefined) return salary;
          }
        }
        return 0;
      };

      const salary = findLevelSalary(levelTreeData, changedValues.positionLevel);

      const form = currentRecord ? drawerForm : modalForm;
      form.setFieldsValue({
        positionSalary: salary,
      });
    }

    // 当员工状态变为离职时，启用离职时间字段
    if (changedValues.employeeStatus !== undefined) {
      if (changedValues.employeeStatus === '2') { // 离职状态
        // 启用离职时间字段
        modalForm.setFieldsValue({ leaveTime: null });
      } else {
        // 在岗状态，清空并禁用离职时间字段
        modalForm.setFieldsValue({ leaveTime: null });
      }
      modalForm.validateFields(['leaveTime']);
    }
  };


  // 显示新增弹窗
  const showModal = () => {
    setIsEditMode(false);
    setIsModalVisible(true);
    modalForm.resetFields();
  };

  // 提交表单（新增或编辑）
  const handleOk = () => {
    modalForm
      .validateFields()
      .then(async (values) => {
        try {
          // 确保 employmentForm 值正确
          const employmentFormValue = values.employmentForm ? parseInt(values.employmentForm, 10) : 3; // 默认为学员

          // 确保员工状态值正确
          const employeeStatusValue = values.employeeStatus === '1' ? 1 : 2;

          if (isEditMode && currentRecord) {
            // 编辑操作
            const editData = {
              id: currentRecord.id,
              idcard: values.idCard,
              birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : '',
              sex: values.gender,
              address: values.hometown,
              record: values.education,
              bank_card: values.bankCard,
              bank: values.bankName,
              agreement_end: values.contractExpireTime
                ? values.contractExpireTime.format('YYYY-MM-DD')
                : '',
              agreement_num: values.contractTerm,
              political_status: values.politicalStatus,
              layout: employmentFormValue, // 使用处理后的值
              status: employeeStatusValue,
              dw_security: values.companySocialSecurity,
              gr_security: values.personalSocialSecurity,
              entry_time: values.entryTime ? values.entryTime.format('YYYY-MM-DD') : '',
              leave_time: values.leaveTime ? values.leaveTime.format('YYYY-MM-DD') : '',
            };

            const res = await editstaff(editData);
            if (res.code === 1) {
              message.success('员工信息更新成功');

              // 1. 更新当前记录
              const updatedRecord = {
                ...currentRecord,
                ...editData,
                tel: values.phone,
                bank: values.bankName,
                bank_card: values.bankCard,
                political_status: values.politicalStatus,
                layout: employmentFormValue,
                status: employeeStatusValue,
                agreement_end: values.contractExpireTime ? values.contractExpireTime.format('YYYY-MM-DD') : '',
                agreement_num: values.contractTerm,
                personal_social_security: values.personalSocialSecurity,
                company_social_security: values.companySocialSecurity,
                entryTime: values.entryTime ? values.entryTime.format('YYYY-MM-DD') : '',
                leave_time: values.leaveTime ? values.leaveTime.format('YYYY-MM-DD') : '',
              };

              // 2. 更新原始数据列表
              const updatedOriginalData = originalTableData.map(item =>
                item.id === currentRecord.id ? updatedRecord : item
              );
              setOriginalTableData(updatedOriginalData);

              // 3. 更新筛选后的表格数据
              const updatedTableData = tableData.map(item =>
                item.id === currentRecord.id ? updatedRecord : item
              );
              setTableData(updatedTableData);

              // 4. 更新当前选中记录和抽屉表单
              setCurrentRecord(updatedRecord);
              drawerForm.setFieldsValue({
                ...updatedRecord,
                phone: values.phone,
                idCard: values.idCard,
                gender: values.gender,
                birthday: values.birthday,
                hometown: values.hometown,
                positionLevel: updatedRecord.grade_title,
                positionSalary: updatedRecord.base_pay,
                education: values.education,
                bankName: values.bankName,
                bankCard: values.bankCard,
                politicalStatus: values.politicalStatus,
                companyName: updatedRecord.account,
                projectName: updatedRecord.title,
                employmentForm: employmentFormValue.toString(),
                employeeStatus: employeeStatusValue.toString(),
                contractExpireTime: values.contractExpireTime,
                contractTerm: values.contractTerm,
                entryTime: values.entryTime,
                leaveTime: values.leaveTime,
                personalSocialSecurity: values.personalSocialSecurity,
                companySocialSecurity: values.companySocialSecurity,
              });
              // 关闭弹窗
              setIsModalVisible(false);
            } else {
              message.error(res.msg || '员工信息更新失败');
            }
          } else {
            // 新增操作
            console.log('新增员工:', values);

            // 处理日期格式并构建符合接口要求的参数
            const filteredData = {
              name: values.name,
              tel: values.phone,
              sex: values.gender,
              idcard: values.idCard,
              birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : '',
              address: values.hometown,
              record: values.education,
              projectid: values.projectName,
              companyid: values.companyName,
              bank_card: values.bankCard,
              bank: values.bankName,
              agreement_end: values.contractExpireTime
                ? values.contractExpireTime.format('YYYY-MM-DD')
                : '',
              agreement_num: values.contractTerm,
              base_pay: values.positionSalary,
              gradeid: values.positionLevel,
              political_status: values.politicalStatus,
              layout: employmentFormValue, // 使用处理后的值
              status: employeeStatusValue,
              leave_time: values.leaveTime ? values.leaveTime.format('YYYY-MM-DD') : '',
              entry_time: values.entryTime ? values.entryTime.format('YYYY-MM-DD') : '',
            };

            // 调用新增员工接口
            const res = await addstaff(filteredData);
            console.log(filteredData);
            console.log(res);

            if (res.code === 1) {
              message.success('添加员工成功');
              // 新增成功后重新获取数据并保留搜索条件
              await fetchTableList();
              handleSearch();
              setIsModalVisible(false);
            } else {
              message.error(res.msg || '添加员工失败');
            }
          }
        } catch (error) {
          console.error('操作失败:', error);
          message.error('操作失败: ' + (error.message || '未知错误'));
        }
      })
      .catch((info) => {
        console.log('验证失败:', info);
      });
  };


  const handleCancel = () => {
    modalForm.resetFields();
    setIsModalVisible(false);
  };

  // 表格行选择配置
  const rowSelection: TableProps<DataType>['rowSelection'] = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys);
    },
  };

  return (
    <PageContainer style={{ backgroundColor: 'white' }}>
      <div className="staffIcon-box">
        <div className="icons-container">
          <Badge count={417}>
            <Button>入职</Button>
          </Badge>
          <Badge count={9}>
            <Button type="primary" danger>
              离职
            </Button>
          </Badge>
          <Badge count={229}>
            <Button>长期派遣</Button>
          </Badge>
          <Badge count={74}>
            <Button>短期派遣</Button>
          </Badge>
          <Badge count={113}>
            <Button>入职</Button>
          </Badge>
          <Badge count={8}>
            <Button>入职</Button>
          </Badge>
          <Button onClick={handleResetSearch}>重置</Button>
          <Button type="primary" danger>
            批量删除
          </Button>
        </div>
        <Button color="green" variant="solid">
          导出员工
        </Button>
        <Button color="primary" variant="solid">
          导入员工
        </Button>
      </div>

      {/* 搜索部分+新增按钮 */}
      <div className="search-add">
        <div className="search-box">
          <Search
            placeholder="请输入员工姓名"
            value={searchParams.name || ''}
            onChange={(e) => setSearchParams(prev => ({ ...prev, name: e.target.value }))}
            onSearch={handleSearch}
            style={{ width: 200 }}
            allowClear
          />
          <Select
            showSearch
            style={{ width: 200, marginLeft: 16 }}
            placeholder="请选择公司"
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={companyList.map((company) => ({
              value: company.id,
              label: company.account,
            }))}
            value={searchParams.company || undefined}
            onChange={(value) => setSearchParams(prev => ({ ...prev, company: value || '' }))}
            allowClear
            onClear={() => setSearchParams(prev => ({ ...prev, company: '' }))}
          />
          <Search
            placeholder="请输入项目名称"
            value={searchParams.project || ''}
            onChange={(e) => setSearchParams(prev => ({ ...prev, project: e.target.value }))}
            onSearch={handleSearch}
            style={{ width: 200, marginLeft: 16 }}
            allowClear
          />
          {/* 优化后的树形档级选择器 */}
          <TreeSelect
            className={styles.treeSelectContainer}
            style={{ width: 200, marginLeft: 16 }}
            value={searchParams.level || undefined}
            treeData={levelTreeData}
            placeholder="请选择档级"
            treeDefaultExpandAll={false}
            onChange={(value) => setSearchParams(prev => ({ ...prev, level: value || '' }))}
            showSearch
            treeNodeFilterProp="title"
            allowClear
            onClear={() => setSearchParams(prev => ({ ...prev, level: '' }))}
          />
          <Select
            style={{ width: 200, marginLeft: 16 }}
            placeholder="请选择证书"
            options={certificateTypes.map((cert) => ({
              value: cert.value,
              label: cert.label,
            }))}
            value={searchParams.certificate || undefined}
            onChange={(value) => setSearchParams(prev => ({ ...prev, certificate: value || '' }))}
            allowClear
            onClear={() => setSearchParams(prev => ({ ...prev, certificate: '' }))}
          />
          <DatePicker
            style={{ width: 200, marginLeft: 16 }}
            value={searchParams.date || null}
            onChange={(date) => setSearchParams(prev => ({ ...prev, date }))}
            onOk={handleSearch}
            picker="month"
            placeholder="请选择月份"
            allowClear
            onClear={() => setSearchParams(prev => ({ ...prev, date: null }))}
          />
          <Button
            type="primary"
            style={{ marginLeft: 16 }}
            onClick={handleSearch}
          >
            搜索
          </Button>
        </div>
        <Button style={{ marginLeft: 16 }} type="primary" onClick={showModal}>
          新增
        </Button>
      </div>
      <div style={{ height: '20px' }}></div>
      <Spin spinning={loading}>
        <Table<DataType>
          bordered
          className={styles.customTable}
          columns={columns}
          dataSource={tableData}
          scroll={{ x: 'max-content', y: 80 * 5 }}
          rowSelection={rowSelection}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            total: tableData.length,
            showTotal: (total) => `共 ${total} 条数据`,
          }}
        />

      </Spin>

      {/* 新增/编辑员工弹窗 - 移除密码字段 */}
      <Modal
        title={isEditMode ? '编辑员工' : '新增员工'}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={900}
        destroyOnHidden={true}
      >
        <Form
          form={modalForm}
          layout="vertical"
          onValuesChange={handleValuesChange}
          initialValues={{
            employmentForm: '3', // 默认为学员
            employeeStatus: '1', // 默认为在岗
          }}
        >
          {/* 第一行：姓名、手机号、证件号码 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: '请输入员工姓名!' }]}
            >
              <Input placeholder="请输入员工姓名" />
            </Form.Item>
            <Form.Item
              name="phone"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号!' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式!' },
              ]}
            >
              <Input placeholder="请输入手机号" maxLength={11} />
            </Form.Item>
            <Form.Item
              name="idCard"
              label="证件号码"
              rules={[
                { required: true, message: '请输入身份证号码!' },
                { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码!' },
              ]}
            >
              <Input placeholder="请输入证件号码" maxLength={18} />
            </Form.Item>
          </div>

          {/* 第二行：性别、生日、籍贯 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="gender"
              label="性别"
              rules={[{ required: true, message: '请先输入身份证号码!' }]}
            >
              <Input disabled placeholder="输入身份证号自动填充" />
            </Form.Item>
            <Form.Item
              name="birthday"
              label="生日"
              rules={[{ required: true, message: '请先输入身份证号码!' }]}
            >
              <DatePicker disabled style={{ width: '100%' }} placeholder="输入身份证号自动填充" />
            </Form.Item>
            <Form.Item
              name="hometown"
              label="籍贯"
              rules={[{ required: true, message: '请输入籍贯!' }]}
            >
              <Input placeholder="请输入籍贯" />
            </Form.Item>
          </div>

          {/* 第三行：岗位档级、岗位工资、学历 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="positionLevel"
              label="岗位档级"
              rules={[{ required: true, message: '请选择岗位档级!' }]}
            >
              <TreeSelect
                style={{ width: '100%' }}
                treeData={levelTreeData}
                placeholder="请选择岗位档级"
                treeDefaultExpandAll={false}
                showSearch
                treeNodeFilterProp="title"
                treeEmptyText="暂无档级数据"
              />
            </Form.Item>
            <Form.Item
              name="positionSalary"
              label="岗位工资"
              rules={[{ required: true, message: '请先选择岗位档级!' }]}
            >
              <Input disabled type="number" placeholder="选择档级后自动填充" />
            </Form.Item>
            <Form.Item
              name="education"
              label="学历"
              rules={[{ required: true, message: '请选择学历!' }]}
            >
              <Select placeholder="请选择学历">
                <Select.Option value="高中">高中</Select.Option>
                <Select.Option value="大专">大专</Select.Option>
                <Select.Option value="本科">本科</Select.Option>
                <Select.Option value="研究生">研究生</Select.Option>
                <Select.Option value="博士">博士</Select.Option>
              </Select>
            </Form.Item>
          </div>

          {/* 第四行：开户行、银行卡号、政治面貌 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="bankName"
              label="开户行"
              rules={[{ required: true, message: '请输入开户行!' }]}
            >
              <Input placeholder="请输入开户行全称" />
            </Form.Item>
            <Form.Item
              name="bankCard"
              label="银行卡号"
              rules={[{ required: true, message: '请输入银行卡号!' }]}
            >
              <Input placeholder="请输入银行卡号" />
            </Form.Item>
            <Form.Item
              name="politicalStatus"
              label="政治面貌"
              rules={[{ required: true, message: '请选择政治面貌!' }]}
            >
              <Select placeholder="请选择政治面貌">
                <Select.Option value="群众">群众</Select.Option>
                <Select.Option value="团员">团员</Select.Option>
                <Select.Option value="党员">党员</Select.Option>
              </Select>
            </Form.Item>
          </div>

          {/* 第五行：公司、项目、用工形式 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="companyName"
              label="公司"
              rules={[{ required: true, message: '请选择公司!' }]}
            >
              <Select placeholder="请选择公司" onChange={handleCompanyChange}>
                {companyList.map((company) => (
                  <Select.Option key={company.id} value={company.id}>
                    {company.account}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="projectName"
              label="项目"
              rules={[{ required: true, message: '请选择项目!' }]}
            >
              <Select placeholder="请选择项目">
                {projectList.map((project) => (
                  <Select.Option key={project.id} value={project.id}>
                    {project.title}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="employmentForm"
              label="用工形式"
              rules={[{ required: true, message: '请选择用工形式!' }]}
            >
              <Select placeholder="请选择用工形式">
                <Select.Option value="3">学员</Select.Option>
                <Select.Option value="1">长期派遣</Select.Option>
                <Select.Option value="2">短期派遣</Select.Option>
              </Select>
            </Form.Item>
          </div>

          {/* 第六行：员工状态、合同到期时间、现合同期限(年) */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="employeeStatus"
              label="员工状态"
              rules={[{ required: true, message: '请选择员工状态!' }]}
            >
              <Select placeholder="请选择员工状态">
                <Select.Option value="1">在岗</Select.Option>
                <Select.Option value="2">离职</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="contractExpireTime"
              label="合同到期时间"
              rules={[{ required: true, message: '请选择合同到期时间!' }]}
            >
              <DatePicker style={{ width: '100%' }} placeholder="请选择合同到期时间" />
            </Form.Item>
            <Form.Item
              name="contractTerm"
              label="现合同期限(年)"
              rules={[{ required: true, message: '请输入合同期限!' }]}
            >
              <Input type="number" placeholder="请输入合同期限" min={1} />
            </Form.Item>
          </div>

          {/* 第七行：个人社保基数、单位社保基数、入职时间 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="personalSocialSecurity"
              label="个人社保基数"
              rules={[{ required: true, message: '请输入个人社保基数!' }]}
            >
              <Input type="number" placeholder="请输入个人社保基数" min={0} />
            </Form.Item>
            <Form.Item
              name="companySocialSecurity"
              label="单位社保基数"
              rules={[{ required: true, message: '请输入单位社保基数!' }]}
            >
              <Input type="number" placeholder="请输入单位社保基数" min={0} />
            </Form.Item>
            <Form.Item
              name="entryTime"
              label="入职时间"
              rules={[{ required: true, message: '请选择入职时间!' }]}
            >

              <DatePicker style={{ width: '100%' }} placeholder="请选择入职时间" />
            </Form.Item>
          </div>

          {/* 第八行：离职时间 - 不占满一整行 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="leaveTime"
              label="离职时间"
              rules={[
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    const status = getFieldValue('employeeStatus');
                    if (status !== '2') {
                      return Promise.resolve();
                    }
                    if (value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('请选择离职时间!'));
                  },
                }),
              ]}
            >
              <DatePicker
                style={{ width: '100%' }}
                placeholder="请选择离职时间"
                disabled={modalForm.getFieldValue('employeeStatus') !== '2'}
              />
            </Form.Item>
            {/* 留空两个位置保持布局一致性 */}
            <div></div>
            <div></div>
          </div>
        </Form>
      </Modal>

      {/* 合同新增/编辑弹窗 - 调整布局和样式 */}
      <Modal
        title={isEditContractMode ? '编辑合同' : '新增合同'}
        open={contractModalVisible}
        onOk={handleContractOk}
        onCancel={() => setContractModalVisible(false)}
        width={900}
        destroyOnHidden={true}
        maskClosable={false}
      >
        <Form
          form={contractForm}
          layout="vertical"
          initialValues={{
            contractType: 'labor',
            status: 'pending',
          }}
        >
          {/* 第一行：合同名称，合同类型，合同编号 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="contractName"
              label="合同名称"
              rules={[{ required: true, message: '请输入合同名称!' }]}
            >
              <Input placeholder="请输入合同名称" />
            </Form.Item>
            <Form.Item
              name="contractType"
              label="合同类型"
              rules={[{ required: true, message: '请选择合同类型!' }]}
            >
              <Select placeholder="请选择合同类型">
                {contractTypeOptions.map((option) => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="contractNumber"
              label="合同编号"
              rules={[{ required: true, message: '请输入合同编号!' }]}
            >
              <Input placeholder="请输入合同编号" />
            </Form.Item>
          </div>

          {/* 第二行：甲方姓名，甲方身份证号，甲方手机号 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="partyAName"
              label="甲方姓名"
              rules={[{ required: true, message: '请输入甲方姓名!' }]}
            >
              <Input placeholder="请输入甲方姓名" />
            </Form.Item>
            <Form.Item
              name="partyAIdCard"
              label="甲方身份证号"
              rules={[
                { required: true, message: '请输入甲方身份证号!' },
                { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码!' },
              ]}
            >
              <Input placeholder="请输入甲方身份证号" maxLength={18} />
            </Form.Item>
            <Form.Item
              name="partyAPhone"
              label="甲方手机号"
              rules={[
                { required: true, message: '请输入甲方手机号!' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式!' },
              ]}
            >
              <Input placeholder="请输入甲方手机号" maxLength={11} />
            </Form.Item>
          </div>

          {/* 第三行：甲方公司全称，甲方机构代码，乙方姓名 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="partyACompany"
              label="甲方公司全称"
              rules={[{ required: true, message: '请输入甲方公司全称!' }]}
            >
              <Input placeholder="请输入甲方公司全称" />
            </Form.Item>
            <Form.Item
              name="partyAOrganizationCode"
              label="甲方机构代码"
              rules={[{ required: true, message: '请输入甲方机构代码!' }]}
            >
              <Input placeholder="请输入甲方机构代码" />
            </Form.Item>
            <Form.Item
              name="partyBName"
              label="乙方姓名"
              rules={[{ required: true, message: '请输入乙方姓名!' }]}
            >
              <Input placeholder="请输入乙方姓名" />
            </Form.Item>
          </div>

          {/* 第四行：乙方身份证号，乙方手机号，执行状态 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="partyBIdCard"
              label="乙方身份证号"
              rules={[
                { required: true, message: '请输入乙方身份证号!' },
                { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码!' },
              ]}
            >
              <Input placeholder="请输入乙方身份证号" maxLength={18} />
            </Form.Item>
            <Form.Item
              name="partyBPhone"
              label="乙方手机号"
              rules={[
                { required: true, message: '请输入乙方手机号!' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式!' },
              ]}
            >
              <Input placeholder="请输入乙方手机号" maxLength={11} />
            </Form.Item>
            <Form.Item
              name="status"
              label="执行状态"
              rules={[{ required: true, message: '请选择执行状态!' }]}
            >
              <Select placeholder="请选择执行状态">
                {contractStatusOptions.map((option) => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          {/* 第五行：开始时间，结束时间 */}
          <div className={styles.formItemRow}>
            <Form.Item
              name="startTime"
              label="开始时间"
              rules={[{ required: true, message: '请选择开始时间!' }]}
            >
              <DatePicker style={{ width: '100%' }} placeholder="请选择开始时间" />
            </Form.Item>
            <Form.Item
              name="endTime"
              label="结束时间"
              rules={[{ required: true, message: '请选择结束时间!' }]}
            >
              <DatePicker style={{ width: '100%' }} placeholder="请选择结束时间" />
            </Form.Item>
          </div>

          {/* 第六行：上传文件 */}
          <div>
            <h3>合同文件上传</h3>
            <Form.Item name="files">
              <Upload
                fileList={fileList}
                beforeUpload={beforeUpload}
                onChange={handleFileChange}
                maxCount={5}
                accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif"
              >
                <div className={styles.uploadZone}>
                  <UploadOutlined />
                  <p style={{ marginTop: 8 }}>
                    点击或拖拽文件至此处上传（支持PDF、Word、Excel、图片格式，最大20MB）
                  </p>
                </div>
              </Upload>
            </Form.Item>
          </div>
        </Form>
      </Modal>

      {/* 详情抽屉 - 调整合同列表中新增按钮位置 */}
      <Drawer
        title={currentRecord ? `${currentRecord.name} 的个人信息` : '员工信息'}
        width={900}
        onClose={onClose}
        open={open}
        styles={{
          body: {
            paddingBottom: 80,
          },
        }}
        extra={
          <Space>
            <Button onClick={handleEdit} type="primary">
              编辑
            </Button>
            <Button onClick={onClose}>关闭</Button>
          </Space>
        }
      >
        <Tabs defaultActiveKey="basic" style={{ marginBottom: 20 }}>
          {/* 基本信息选项卡 */}
          <TabPane tab="基本信息" key="basic">
            <Form
              form={drawerForm}
              layout="vertical"
              onValuesChange={handleValuesChange}
              initialValues={
                currentRecord || {
                  employmentForm: '正式员工',
                  employeeStatus: '在职',
                }
              }
            >
              {/* 第一行：姓名，性别，籍贯 */}
              <div className={styles.formItemRow}>
                <Form.Item name="name" label="姓名">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="gender" label="性别">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="hometown" label="籍贯">
                  <Input disabled />
                </Form.Item>
              </div>

              {/* 第二行：学历，电话，形象 */}
              <div className={styles.formItemRow}>
                <Form.Item name="education" label="学历">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="phone" label="电话">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="image" label="形象">
                  {currentRecord?.imageUrl ? (
                    <Avatar src={currentRecord.imageUrl} alt="员工照片" size="large" />
                  ) : (
                    <Input disabled placeholder="暂无信息" />
                  )}
                </Form.Item>
              </div>

              {/* 第三行：身份证号，银行卡号，所在公司 */}
              <div className={styles.formItemRow}>
                <Form.Item name="idCard" label="身份证号">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="bankCard" label="银行卡号">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="companyName" label="所在公司">
                  <Input disabled />
                </Form.Item>
              </div>

              {/* 第四行：用工形式，档级，基本工资 */}
              <div className={styles.formItemRow}>
                <Form.Item name="employmentForm" label="用工形式">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="positionLevel" label="档级">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="positionSalary" label="基本工资">
                  <Input disabled prefix="¥" />
                </Form.Item>
              </div>

              {/* 第五行：创建时间，所属项目，开户行 */}
              <div className={styles.formItemRow}>
                <Form.Item name="create_time" label="创建时间">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="projectName" label="所属项目">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="bankName" label="开户行">
                  <Input disabled />
                </Form.Item>
              </div>

              {/* 第六行：到期时间，签订年数 */}
              <div className={styles.formItemRow}>
                <Form.Item name="contractExpireTime" label="到期时间">
                  <DatePicker disabled style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item name="contractTerm" label="签订年数">
                  <Input disabled />
                </Form.Item>
                {/* 留空一个位置保持布局一致性 */}
                <div></div>
              </div>

              {/* 第七行：个人社保基数，单位社保基数，入职时间 */}
              <div className={styles.formItemRow}>
                <Form.Item name="personalSocialSecurity" label="个人社保基数">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="companySocialSecurity" label="单位社保基数">
                  <Input disabled />
                </Form.Item>
                <Form.Item name="entryTime" label="入职时间">
                  <DatePicker disabled style={{ width: '100%' }} />
                </Form.Item>
              </div>

              {/* 第八行：离职时间 - 不占满一整行 */}
              <div className={styles.formItemRow}>
                <Form.Item name="leaveTime" label="离职时间">
                  <DatePicker disabled style={{ width: '100%' }} />
                </Form.Item>
                {/* 留空两个位置保持布局一致性 */}
                <div></div>
                <div></div>
              </div>
            </Form>
          </TabPane>

          {/* 员工合同选项卡 - 调整新增按钮位置 */}
          <TabPane tab="员工合同" key="contract">
            <div>
              <div style={{ marginBottom: 16 }}>
                <div style={{ lineHeight: '1.5', color: '#2C3E50', marginBottom: 12 }}>
                  <p>操作说明：</p>
                  <p>1、点击新增创建合同</p>
                  <p>2、点击签署，发起合同签章，甲乙双方根据收到的短信链接点击后进行签署</p>
                  <p>3、甲乙双方签署成功后，点击归档，合同签署流程结束</p>
                  <p>4、乙方尚未签署时，甲方可撤回修改重新发起签署</p>
                </div>

                {/* 新增合同按钮在操作说明下面，表格上面 */}
                <Button
                  type="primary"
                  icon={<FileTextOutlined />}
                  onClick={showContractModal}
                  style={{ marginBottom: 16 }}
                >
                  新增合同
                </Button>

                {currentRecord?.contract_between && currentRecord.contract_between.length > 0 ? (
                  <Table
                    dataSource={currentRecord.contract_between}
                    columns={contractColumns}
                    pagination={false}
                    scroll={{ x: 'max-content' }}
                  />
                ) : (
                  <div style={{ textAlign: 'center', padding: 30 }}>
                    <p>暂无合同信息，请点击"新增合同"按钮创建</p>
                  </div>
                )}
              </div>
            </div>
          </TabPane>

          {/* 工资社保选项卡 */}
          <TabPane tab="工资社保" key="salary">
            <div style={{ padding: 20 }}>
              <div className={styles.formItemRow}>
                <Form.Item label="基本工资">
                  <Input value={currentRecord?.positionSalary} disabled />
                </Form.Item>
                <Form.Item label="个人社保基数">
                  <Input value={currentRecord?.personal_social_security} disabled />
                </Form.Item>
                <Form.Item label="单位社保基数">
                  <Input value={currentRecord?.company_social_security} disabled />
                </Form.Item>
              </div>

              <div style={{ marginTop: 20 }}>
                <h4>社保详情</h4>
                <p>此处显示社保缴纳详情...</p>
              </div>
            </div>
          </TabPane>

          {/* 证书列表选项卡 - 更新为指定证书类型 */}
          <TabPane tab="证书列表" key="certificates">
            <div style={{ padding: 20 }}>
              {currentRecord?.certid && currentRecord.certid.length > 0 ? (
                <Table
                  dataSource={currentRecord.certid.map((item, index) => ({
                    key: index,
                    ...item,
                  }))}
                  columns={[
                    { title: '证书名称', dataIndex: 'certname', key: 'certname' },
                    { title: '证书编号', dataIndex: 'certclassid', key: 'certclassid' },
                    { title: '获取时间', dataIndex: 'obtain_time', key: 'obtain_time' },
                  ]}
                  pagination={false}
                />
              ) : (
                <p>暂无证书信息</p>
              )}

              {/* 可以添加"添加证书"按钮，实现添加证书功能 */}
              <Button
                type="primary"
                style={{ marginTop: 16 }}
                onClick={() => message.info('添加证书功能待实现')}
              >
                添加证书
              </Button>
            </div>
          </TabPane>
        </Tabs>
      </Drawer>
    </PageContainer>
  );
};

export default Staff;
